package com.stock_t.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.stock_t.entity.StockTTransaction;
import com.stock_t.page.TableDataInfo;
import com.stock_t.service.StockTTransactionService;
import com.stock_t.utils.PageUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 股票T交易控制器
 */
@Slf4j
@RestController
@RequestMapping("/stock/t/transaction")
public class StockTTransactionController {

    @Autowired
    private StockTTransactionService stockTTransactionService;

    /**
     * 校验和修正日期字符串，将无效日期修正为当月最后一天
     * @param dateStr 日期字符串，格式为yyyy-MM-dd
     * @return 修正后的日期字符串
     */
    private String validateAndFixDate(String dateStr) {
        if (dateStr == null || dateStr.trim().isEmpty()) {
            return dateStr;
        }
        
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        sdf.setLenient(false); // 严格模式，不允许无效日期
        
        try {
            // 尝试解析日期
            sdf.parse(dateStr);
            return dateStr; // 日期有效，直接返回
        } catch (Exception e) {
            // 日期无效，修正为当月最后一天
            try {
                String[] parts = dateStr.split("-");
                if (parts.length == 3) {
                    int year = Integer.parseInt(parts[0]);
                    int month = Integer.parseInt(parts[1]) - 1; // Calendar月份从0开始
                    
                    Calendar calendar = Calendar.getInstance();
                    calendar.set(Calendar.YEAR, year);
                    calendar.set(Calendar.MONTH, month);
                    
                    // 设置为当月最后一天
                    int lastDay = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
                    calendar.set(Calendar.DAY_OF_MONTH, lastDay);
                    
                    String fixedDate = sdf.format(calendar.getTime());
                    log.warn("日期{}无效，已修正为当月最后一天：{}", dateStr, fixedDate);
                    return fixedDate;
                }
            } catch (Exception ex) {
                log.error("修正日期失败：{}", dateStr, ex);
            }
            return dateStr; // 修正失败，返回原值
        }
    }
       /**
     * 获取股票T交易列表
     */
    @PostMapping("/list")
    public Map<String, Object> list(@RequestBody Map<String, Object> params) {
        log.info("查询参数:{}", params);
        
        String stockCode = (String) params.get("stockCode");
        String startDate = (String) params.get("startDate");
        String endDate = (String) params.get("endDate");
        
        // 修正无效日期
        startDate = validateAndFixDate(startDate);
        endDate = validateAndFixDate(endDate);
        
        QueryWrapper<StockTTransaction> queryWrapper = new QueryWrapper<>();
        
        // 添加股票代码条件
        if (stockCode != null && !stockCode.trim().isEmpty() && !stockCode.equals("-1")) {
            queryWrapper.eq("stock_code", stockCode);
        }
        
        // 添加日期范围条件
        if (startDate != null && !startDate.trim().isEmpty()) {
            queryWrapper.ge("transaction_date", startDate);
        }
        
        if (endDate != null && !endDate.trim().isEmpty()) {
            queryWrapper.le("transaction_date", endDate);
        }
        
        // 按交易日期升序排序
        queryWrapper.orderByAsc("transaction_date");
        
        List<StockTTransaction> list = stockTTransactionService.list(queryWrapper);
        
        Map<String, Object> result = new HashMap<>();
        result.put("code", 200);
        result.put("data", list);
        result.put("msg", "success");
        return result;
    }
    
    /**
     * 分页查询股票T交易
     */
    @PostMapping("/page")
    public TableDataInfo page(@RequestBody StockTTransaction stockTTransaction) {
        // 使用PageUtils开启分页
        Page<StockTTransaction> page = PageUtils.startPage();
        log.info("分页查询股票T交易，查询条件：{}", stockTTransaction);
        // 构建查询条件
        QueryWrapper<StockTTransaction> queryWrapper = new QueryWrapper<>(stockTTransaction);
        stockTTransactionService.page(page, queryWrapper);
        
        return PageUtils.getDataTable(page);
    }
    
    /**
     * 根据ID获取股票T交易
     */
    @GetMapping("/{id}")
    public Map<String, Object> getById(@PathVariable("id") Long id) {
        StockTTransaction stockTTransaction = stockTTransactionService.getById(id);
        
        Map<String, Object> result = new HashMap<>();
        if (stockTTransaction != null) {
            result.put("code", 200);
            result.put("data", stockTTransaction);
            result.put("msg", "success");
        } else {
            result.put("code", 404);
            result.put("msg", "股票T交易不存在");
        }
        
        return result;
    }
    
    /**
     * 保存股票T交易（新增或更新）
     */
    @PostMapping("/save")
    public Map<String, Object> save(@RequestBody StockTTransaction stockTTransaction) {
        boolean success = stockTTransactionService.saveOrUpdate(stockTTransaction);
        
        Map<String, Object> result = new HashMap<>();
        if (success) {
            result.put("code", 200);
            result.put("msg", "保存成功");
        } else {
            result.put("code", 500);
            result.put("msg", "保存失败");
        }
        
        return result;
    }
    
    /**
     * 更新股票T交易
     */
    @PutMapping("/update")
    public Map<String, Object> update(@RequestBody StockTTransaction stockTTransaction) {
        // 确保记录存在
        StockTTransaction existStockTTransaction = stockTTransactionService.getById(stockTTransaction.getId());
        
        Map<String, Object> result = new HashMap<>();
        if (existStockTTransaction == null) {
            result.put("code", 404);
            result.put("msg", "股票T交易不存在");
            return result;
        }
        
        boolean success = stockTTransactionService.updateById(stockTTransaction);
        
        if (success) {
            result.put("code", 200);
            result.put("msg", "更新成功");
        } else {
            result.put("code", 500);
            result.put("msg", "更新失败");
        }
        
        return result;
    }
    
    /**
     * 删除股票T交易
     */
    @DeleteMapping("/{id}")
    public Map<String, Object> delete(@PathVariable("id") Long id) {
        // 确保记录存在
        StockTTransaction existStockTTransaction = stockTTransactionService.getById(id);
        
        Map<String, Object> result = new HashMap<>();
        if (existStockTTransaction == null) {
            result.put("code", 404);
            result.put("msg", "股票T交易不存在");
            return result;
        }
        
        boolean success = stockTTransactionService.removeById(id);
        
        if (success) {
            result.put("code", 200);
            result.put("msg", "删除成功");
        } else {
            result.put("code", 500);
            result.put("msg", "删除失败");
        }
        
        return result;
    }
    
    /**
     * 批量删除股票T交易
     */
    @DeleteMapping("/batch")
    public Map<String, Object> batchDelete(@RequestBody List<Long> ids) {
        if (ids == null || ids.isEmpty()) {
            Map<String, Object> result = new HashMap<>();
            result.put("code", 400);
            result.put("msg", "请选择要删除的记录");
            return result;
        }
        
        boolean success = stockTTransactionService.removeByIds(ids);
        
        Map<String, Object> result = new HashMap<>();
        if (success) {
            result.put("code", 200);
            result.put("msg", "批量删除成功");
        } else {
            result.put("code", 500);
            result.put("msg", "批量删除失败");
        }
        
        return result;
    }
    
    /**
     * 获取指定日期和股票的做T总收益
     */
    @PostMapping("/total-t-profit-by-stock")
    public Map<String, Object> getTotalTProfitByStockAndDate(@RequestBody Map<String, Object> params) {
        String stockCode = (String) params.get("stockCode");
        String transactionDate = (String) params.get("transactionDate");
        
        Map<String, Object> result = new HashMap<>();
        
        if (stockCode == null || transactionDate == null) {
            result.put("code", 400);
            result.put("msg", "股票代码和交易日期不能为空");
            return result;
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            // 调用service层计算指定日期和股票的做T总收益
            BigDecimal totalProfit = stockTTransactionService.getTotalTProfitByDateAndStock(sdf.parse(transactionDate), stockCode);
            
            result.put("code", 200);
            result.put("data", totalProfit);
            result.put("msg", "success");
        } catch (Exception e) {
            log.error("获取指定日期和股票的做T总收益失败", e);
            result.put("code", 500);
            result.put("msg", "获取做T收益失败");
        }
        
        return result;
    }

    /**
     * 获取指定日期和股票的做T总收益
     */
    @PostMapping("/totalTProfitByStockCode")
    public Map<String, Object> totalTProfitByStockCode(@RequestBody Map<String, Object> params) {
        String stockCode = (String) params.get("stockCode");
        Map<String, Object> result = new HashMap<>();
        if (stockCode == null) {
            result.put("code", 400);
            result.put("msg", "股票代码和交易日期不能为空");
            return result;
        }
        try {
            // 调用service层计算指定日期和股票的做T总收益
            BigDecimal totalProfit = stockTTransactionService.getTotalTProfitByStockCode(stockCode);
            result.put("code", 200);
            result.put("data", totalProfit);
            result.put("msg", "success");
        } catch (Exception e) {
            log.error("获取指定日期和股票的做T总收益失败", e);
            result.put("code", 500);
            result.put("msg", "获取做T收益失败");
        }
        return result;
    }
}